//
//  JFriendCircleController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/21.
//  Copyright © 2017年 jun. All rights reserved.
//

/// 圈聊
#import "JFriendCircleController.h"
#import "JDelegateController.h"

@interface JFriendCircleController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *picBtn;
@property (nonatomic, strong) UIView *nameView;
@property (nonatomic, strong) UIView *textContectView;
@property (nonatomic, strong) UIView *dalegateView;
@property (nonatomic, strong) UIButton *submitBtn;
@property (nonatomic, strong) UITextField *nameText;
@property (nonatomic, strong) UITextView *DescriptionText;

@property (nonatomic, strong) NSMutableDictionary *paramerDic; // 参数字典

@end

@implementation JFriendCircleController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    self.titleLabel.text = @"建圈子";
    self.leftButton.hidden = NO;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    [self setConfigBgView];
    
}

- (void)setConfigBgView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.navigationController.navigationBar.translucent = NO;
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWindowH, self.contentView.height)];
    _scrollView.backgroundColor = kRGBColor(245, 245, 245);
    [self.contentView addSubview:_scrollView];
    
    UIButton *picBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    picBtn.frame = CGRectMake(0, 10, kWindowW, 40);
    picBtn.titleLabel.font = kFONT_TITLE(16);
    [picBtn setImage:[UIImage imageNamed:@"gophoto"] forState:UIControlStateNormal];
    [picBtn setTitle:@" 上传图片" forState:UIControlStateNormal];
    [picBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [picBtn addTarget:self action:@selector(picBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:picBtn];
    _picBtn = picBtn;
    
    UIView *nameView = [[UIView alloc]initWithFrame:CGRectMake(0, _picBtn.bottom + 10, kWindowW, 40)];
    nameView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:nameView];
    _nameView = nameView;
    
    YYLabel *nameText = [YYLabel new];
    nameText.top = 0;
    nameText.left = 15;
    nameText.size = CGSizeMake(70, nameView.height);
    nameText.font = kFONT_TITLE(15);
    nameText.text = @"圈子名称:";
    nameText.textColor = kRGBColor(150, 150, 150);
    [nameView addSubview:nameText];
    
    UITextField *textfield = [[UITextField alloc]initWithFrame:CGRectMake(nameText.right + 5, 0, kWindowW - nameText.right - 20, nameView.height)];
    textfield.font = kFONT_TITLE(14);
    [nameView addSubview:textfield];
    _nameText = textfield;
    
    CALayer *line = [CALayer layer];
    line.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line.frame = CGRectMake(0, nameView.bottom - 0.5 , kWindowW, 0.5);
    [nameView.layer addSublayer:line];
    
    _textContectView = [[UIView alloc]initWithFrame:CGRectMake(0, nameView.bottom + 10, kWindowW, 200)];
    _textContectView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_textContectView];
    
    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(15, 10, kWindowW - 30, _textContectView.height - 20)];
    textView.backgroundColor = kRGBColor(245, 245, 245);
    textView.font = [UIFont systemFontOfSize:14];
    [_textContectView addSubview:textView];
    _DescriptionText = textView;
    
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"描述您希望什么人加入这个圈子...";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = kRGBColor(206, 206, 210);
    placeHolderLabel.font = kFONT_TITLE(14);
    [placeHolderLabel sizeToFit];
    [textView addSubview:placeHolderLabel];
    
    // same font
    textView.font = [UIFont systemFontOfSize:14];
    placeHolderLabel.font = [UIFont systemFontOfSize:14];
    
    [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    
    UIView *delegateView = [[UIView alloc]initWithFrame:CGRectMake(0, _textContectView.bottom + 10, kWindowW, 40)];
    delegateView.backgroundColor = [UIColor clearColor];
    [_scrollView addSubview:delegateView];
    _dalegateView = delegateView;
    
    UIButton *selBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selBtn.frame = CGRectMake(0, 5, 30, 30);
    [selBtn setImage:[UIImage imageNamed:@"selBtn_n"] forState:UIControlStateNormal];
    [selBtn setImage:[UIImage imageNamed:@"selBtn_h"] forState:UIControlStateSelected];
    selBtn.selected = NO;
    selBtn.tag = 10;
    [selBtn addTarget:self action:@selector(selBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [delegateView addSubview:selBtn];
    
    UILabel *textLabel = [UILabel new];
    textLabel.top = 0;
    textLabel.left = selBtn.right;
    textLabel.size = CGSizeMake(70, delegateView.height);
    textLabel.font = kFONT_TITLE(14);
    textLabel.text = @"是否阅读，并同意此";
    textLabel.textColor = kRGBColor(150, 150, 150);
    
    [textLabel sizeToFit];
    textLabel.top = 0;
    textLabel.left = selBtn.right;
    textLabel.size = CGSizeMake(textLabel.width, delegateView.height);
    
    [delegateView addSubview:textLabel];

    YYLabel *delabel = [YYLabel new];
    delabel.top = 0;
    delabel.left = textLabel.right;
    delabel.size = CGSizeMake(34, delegateView.height);
    delabel.text = @"协议";
    delabel.textColor = [UIColor redColor];
    delabel.font = kFONT_TITLE(14);
    [delegateView addSubview:delabel];
    
    delabel.textTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        JDelegateController *vc = [[JDelegateController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    };
 
    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(15, _dalegateView.bottom + 40 , kWindowW - 30, 40);
    submitBtn.backgroundColor = [UIColor redColor];
    [submitBtn setTitle:@"创建" forState:UIControlStateNormal];
    submitBtn.layer.cornerRadius = 5;
    
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:submitBtn];
    _submitBtn = submitBtn;
}

- (void)picBtnClick
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self xiangjiMethod];
    }];
    
    UIAlertAction *picAction = [UIAlertAction actionWithTitle:@"手机相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self xiangceMethod];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVC addAction:cAction];
    [alertVC addAction:picAction];
    [alertVC addAction:cancelAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)selBtnClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
}

- (void)submitBtnClick:(UIButton *)btn
{
    if (_nameText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入圈聊名"];
        return;
    }
    if (_DescriptionText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入圈聊描述内容"];
        return;
    }
    
    UIButton *selbtn = [_scrollView viewWithTag:10];
    if (selbtn.selected == NO) {
        [SVProgressHUD showErrorWithStatus:@"请阅读协议"];
        return;
    }
    
    if (![self.paramerDic objectForKey:@"PIC"]) {
        [SVProgressHUD showErrorWithStatus:@"请上传您的圈聊图片"];
        return;
    }
    
    [self.paramerDic setObject:_nameText.text forKey:@"Name"];
    [self.paramerDic setObject:_DescriptionText.text forKey:@"Description"];

    btn.enabled = NO;
    
    [SVProgressHUD showWithStatus:@"创建中。。。"];

    
    NSString *url = @"Cirle/AddSocialHub";
    [JNetManager subBeautifulSocialHubRequedtUrl:url
                                          dicPar:self.paramerDic
                                         success:^(id response) {
                                             if ([response integerValue] == 1) {
                                                 [SVProgressHUD showSuccessWithStatus:@"创建成功,信息需要审核后才能发布"];
                                                 [self.navigationController popViewControllerAnimated:YES];
                                             }
                                         } failure:^(NSString *err) {
                                             btn.enabled = YES;
                                             [SVProgressHUD showErrorWithStatus:err];
                                         }];
    
    
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [super leftButtonClick:leftButton];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)xiangjiMethod {
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        //        self.imagePC = imagePickerController;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;//no
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.showsCameraControls  = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else{
        
        //        jHUDNormal(@"您的设备不支持照相功能!")
    }
}

- (void)xiangceMethod {
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }else if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    
}

//#pragma mark  imagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *newImg=[self imageWithImageSimple:image scaledToSize:CGSizeMake(kWindowW - 30, 300)];
    
    _picBtn.frame = CGRectMake(15, 10, kWindowW - 30, 300);
    [_picBtn setTitle:@"" forState:UIControlStateNormal];
    [_picBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [_picBtn setBackgroundImage:newImg forState:UIControlStateNormal];
    
    NSData *data = UIImageJPEGRepresentation(newImg, 0.5f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    JPicModel *picModel = [JPicModel new];
    picModel.MimeType = @"image/jpeg";
    picModel.TitleAttribute = encodedImageStr;
    picModel.SeoFilename = @"";
    
    if ([self.paramerDic objectForKey:@"PIC"]) {
        [self.paramerDic removeObjectForKey:@"PIC"];
        [self.paramerDic setObject:picModel.mj_keyValues forKey:@"PIC"];
    }
    else
    {
        [self.paramerDic setObject:picModel.mj_keyValues forKey:@"PIC"];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self setScrollViewContentSize];
}

- (UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize {
    newSize.height=image.size.height*(newSize.width/image.size.width);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;
}


- (void)setScrollViewContentSize
{
    _nameView.frame  = CGRectMake(0, _picBtn.bottom + 10, kWindowW, 40);
    _textContectView.frame = CGRectMake(0, _nameView.bottom + 10, kWindowW, 200);
    _dalegateView.frame = CGRectMake(0, _textContectView.bottom + 10, kWindowW, 40);
    _submitBtn.frame = CGRectMake(15, _dalegateView.bottom + 40, kWindowW - 30, 40);
    
    _scrollView.contentSize = CGSizeMake(kWindowW, _submitBtn.bottom + 50);
}


- (NSMutableDictionary *)paramerDic
{
    if (_paramerDic == nil) {
        _paramerDic = [NSMutableDictionary dictionary];
        [_paramerDic setObject:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"CustomerId"];
        [_paramerDic setObject:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"UserId"];

    }
    return _paramerDic;
    
    
//CustomerId:1,
//UserId:1,
//    "Name": ""，
//    "Description": ""，
//    "PIC":{ //图片必填
//    MimeType:"image/jpeg", /固定值
//    SeoFilename:"", //固定值为空
//    TitleAttribute:"" //base64的内容
//    }

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
